package service.impl;

import constant.Constant;
import dao.UserDao;
import entity.User;
import exception.DuplicateUsernameException;
import exception.UserDisabledException;
import exception.UserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import service.UserService;
import util.MD5Util;

import java.util.Date;

@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public void regist(User user) throws DuplicateUsernameException {
        User u=userDao.selectByUsername(user.getUsername());
        if(u!=null){
            throw new DuplicateUsernameException("用户名已存在");
        }
        user.setRegistDate(new Date());
        user.setStatus(Constant.UserStatus.USER_STATUS_ENABLE);
        user.setPassword(MD5Util.md5(user.getPassword()));
        userDao.insert(user);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public User login(String username, String password) throws UserNotFoundException, UserDisabledException {
        User user=userDao.selectByUsernameAndPassword(username,MD5Util.md5(password));
        if(user==null){
            throw new UserNotFoundException("用户名或密码错误");
        }
        if(Constant.UserStatus.USER_STATUS_DISABLE.equals(user.getStatus())){
            throw new UserDisabledException("用户已被禁用");
        }
        return user;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public void validateUsername(String username) throws DuplicateUsernameException {
        User user=userDao.selectByUsername(username);
        if(user!=null){
            throw new DuplicateUsernameException("用户名已存在");
        }
    }
}
